from fastapi import APIRouter, Depends, HTTPException
from services.neo4j_service import get_neo4j_service, Neo4jService
from models.node import UpdateNodeRequest

router = APIRouter(
    prefix="/nodes",
    tags=["nodes"],
    responses={404: {"description": "Not found"}},
)

@router.get("/search/")
async def search_nodes(search_string: str, neo4j_service: Neo4jService = Depends(get_neo4j_service)):
    """根据字符串搜索节点"""
    if not search_string or len(search_string) < 2:
        raise HTTPException(status_code=400, detail="搜索字符串至少需要2个字符")
    
    nodes = neo4j_service.search_nodes_by_string(search_string)
    return {"count": len(nodes), "nodes": nodes}

@router.get("/{node_id}")
async def get_node(node_id: str, neo4j_service: Neo4jService = Depends(get_neo4j_service)):
    """获取节点及其关系"""
    node_data = neo4j_service.get_node_with_relations(node_id)
    if not node_data:
        raise HTTPException(status_code=404, detail="节点不存在")
    return node_data

@router.put("/{node_id}")
async def update_node(
    node_id: str,
    request: UpdateNodeRequest,
    neo4j_service: Neo4jService = Depends(get_neo4j_service)
):
    """更新节点属性"""
    if request.node_id != node_id:
        raise HTTPException(status_code=400, detail="节点ID不匹配")
    
    success = neo4j_service.update_node_properties(node_id, request.properties)
    if not success:
        raise HTTPException(status_code=500, detail="更新节点失败")
    
    return {"success": True, "message": "节点更新成功"}